package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.prototypes.CardSection;
import it.gmariotti.cardslib.library.prototypes.SectionedCardAdapter;
import it.gmariotti.cardslib.library.view.CardListView;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.AppUpdateUICard;
import com.jy.appmarket.cards.AppUpdateUICard.AppUpdateUICardCallBack;
import com.jy.appmarket.database.AppUpdateDatabase;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.model.AppUpdateModel;
import com.jy.appmarket.notification.AppUpdateNotification;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.view.LoadingView;
import com.umeng.analytics.MobclickAgent;

public class AppUpdateActivity extends DownloadActivity implements AppUpdateUICardCallBack {

	// private static final String TAG = "AppUpdateActivity";

	private List<AppUpdateModel> mOrgUpdateList = null;

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();

	private SectionedCardAdapter mSectionAdapter;
	private LoadingView mLoadingView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_update_layout);
		Intent intent = getIntent();
		if (intent.getExtras() != null) {
			if (AppUpdateNotification.class.getName().equals(intent.getExtras().get("from"))) {
				AppMarketApplication.appUpdateNotificationShowing = false;
			}
		}
		// 修正数据不同步带来的错误
		AppUpdateDatabase db = AppUpdateDatabase.getInstance(this);
		db.correctAppUpdatesDatas(this);

		initTitle();
		initListView();
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);

		if (mListview.getAdapter() != null) {
			mSectionAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(getResources().getString(R.string.app_update));
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initListView() {
		mLoadingView = findViewById(R.id.loading_view_layout);
		mLoadingView.showEmptyView("没有应用需要升级");

		mListview = findViewById(R.id.app_update_listview);
		// mListview.setEmptyView(mLoadingView);
		mListview.needToRefreshOnFooter(false);
		mListview.needToRefreshOnHeader(false);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onFileDownloadServiceConnected(DownloadService service) {
		loadData(true);
	}

	private void loadData(boolean isUpdateUi) {
		AppUpdateDatabase db = AppUpdateDatabase.getInstance(this);
		mOrgUpdateList = db.getAllUpdatesOrderBy(AppUpdateDatabase.COL_LASTMODIFIED, true, true);

		if (mOrgUpdateList.size() == 0) {
			mListview.setVisibility(View.GONE);
			mLoadingView.setVisibility(View.VISIBLE);

			return;
		} else {
			mListview.setVisibility(View.VISIBLE);
			mLoadingView.setVisibility(View.GONE);
		}

		List<CardSection> sections = new ArrayList<CardSection>();
		ArrayList<Card> normalCardList = new ArrayList<Card>();
		ArrayList<Card> ignoreCardList = new ArrayList<Card>();

		mCardsArray.clear();

		for (AppUpdateModel am : mOrgUpdateList) {
			AppUpdateModelWithDownload aumd = new AppUpdateModelWithDownload();
			aumd.aum = am;

			AppUpdateUICard uiCard = new AppUpdateUICard(this, aumd, this);
			uiCard.setApkSource(new ApkSource("appUpdate", 0, null));

			if (am.isIgnore()) {
				ignoreCardList.add(uiCard);
			} else {
				normalCardList.add(uiCard);
			}
		}

		if (normalCardList.size() != 0) {
			sections.add(new CardSection(0, "可更新(" + normalCardList.size() + ")"));
			mCardsArray.addAll(normalCardList);
		}

		if (ignoreCardList.size() != 0) {
			sections.add(new CardSection(normalCardList.size(), "已忽略(" + ignoreCardList.size() + ")"));
			mCardsArray.addAll(ignoreCardList);
		}

		if (!isUpdateUi) {
			return;
		}

		if (mListview.getAdapter() == null) {
			mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
			mCardsAdapter.setInnerViewTypeCount(100);
			mSectionAdapter = new SectionedCardAdapter(this, mCardsAdapter);
			CardSection[] dummy = new CardSection[sections.size()];
			mSectionAdapter.setCardSections(sections.toArray(dummy));
			mListview.setExternalAdapter(mSectionAdapter, mCardsAdapter);
		} else {
			CardSection[] dummy = new CardSection[sections.size()];
			mSectionAdapter.setCardSections(sections.toArray(dummy));
			mSectionAdapter.notifyDataSetChanged();
		}
	}

	public static class AppUpdateModelWithDownload {
		public long speed;
		public long downloadedSize;
		public AppUpdateModel aum;
	}

	@Override
	public void onNeedToReloadData(AppUpdateModelWithDownload data) {
		loadData(true);
	}

	@Override
	public void onNeedToInstallApp(String downloadId) {
		DownloadItem di = getDownloadById(downloadId);
		if (di == null) {
			return;
		}

		installApk(di);

	}

	@Override
	public void onNeedToStartDownload(String downloadId) {
		startDownload(downloadId);
		if (DownloadUtils.isMobileNetwork(this)) {
			Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onNeedToStopDownload(String downloadId) {
		stopDownload(downloadId);
	}

	@Override
	public void onNeedToAddNewDownload(AppUpdateModel m) {
		addDownload(m.getDownloadUrl(), m.getTitle(), m.getPackageName(), m.getVersionName(), m.getVersionCode(),
				m.getFileMd5(), m.getIconPath(), ApkSource.toSourceString(new ApkSource("appUpdate", 0, null)));

		if (DownloadUtils.isMobileNetwork(this)) {
			Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onNeedToCorrectOutOfDateDownload(AppUpdateModel m) {

		removeOutofDateDownloads(m.getPackageName());
		addDownload(m.getDownloadUrl(), m.getTitle(), m.getPackageName(), m.getVersionName(), m.getVersionCode(),
				m.getFileMd5(), m.getIconPath(), ApkSource.toSourceString(new ApkSource("appUpdate", 0, null)));

		if (DownloadUtils.isMobileNetwork(this)) {
			Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onPackageInstalled(String pkgName) {
		super.onPackageInstalled(pkgName);

		if (mCardsArray == null || mCardsArray.size() == 0) {
			return;
		}

		for (Card c : mCardsArray) {
			if (!(c instanceof AppUpdateUICard)) {
				continue;
			}
			AppUpdateUICard uicard = (AppUpdateUICard) c;
			AppUpdateModel m = uicard.getAppUpdateModel();
			if (m == null) {
				continue;
			}

			if (m.getPackageName().equals(pkgName)) {
				onNeedToReloadData(null);
				return;
			}
		}
	}

	@Override
	protected void onPackageUninstalled(String pkgName) {
		super.onPackageUninstalled(pkgName);
		if (mCardsArray == null || mCardsArray.size() == 0) {
			return;
		}

		for (Card c : mCardsArray) {
			if (!(c instanceof AppUpdateUICard)) {
				continue;
			}
			AppUpdateUICard uicard = (AppUpdateUICard) c;
			AppUpdateModel m = uicard.getAppUpdateModel();
			if (m == null) {
				continue;
			}

			if (m.getPackageName().equals(pkgName)) {
				onNeedToReloadData(null);
				return;
			}
		}
	}

	@Override
	public void onProgressChanged(String id, long downloadedBytes, long speed) {
		super.onProgressChanged(id, downloadedBytes, speed);

		if (mCardsArray == null || mCardsArray.size() == 0) {
			return;
		}

		for (Card c : mCardsArray) {
			if (!(c instanceof AppUpdateUICard)) {
				continue;
			}
			AppUpdateUICard uicard = (AppUpdateUICard) c;
			AppUpdateModel m = uicard.getAppUpdateModel();
			if (m == null) {
				continue;
			}

			String dlId = DownloadUtils.generateDownloadId(m.getPackageName(), m.getVersionCode());
			if (dlId.equals(id)) {
				uicard.onProgressChanged(id, downloadedBytes, speed);
				mSectionAdapter.notifyDataSetChanged();
				return;
			}
		}
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		super.onDownloadCreated(di);
		if (mCardsArray == null || mCardsArray.size() == 0) {
			return;
		}

		for (Card c : mCardsArray) {
			if (!(c instanceof AppUpdateUICard)) {
				continue;
			}
			AppUpdateUICard uicard = (AppUpdateUICard) c;
			AppUpdateModel m = uicard.getAppUpdateModel();
			if (m == null) {
				continue;
			}

			String dlId = DownloadUtils.generateDownloadId(m.getPackageName(), m.getVersionCode());
			if (dlId.equals(di.getId())) {
				uicard.onDownloadCreated(di);
				mSectionAdapter.notifyDataSetChanged();
				return;
			}
		}
	}

	@Override
	public void onDownloadChanged(DownloadItem di) {
		super.onDownloadChanged(di);
		if (mCardsArray == null || mCardsArray.size() == 0) {
			return;
		}

		for (Card c : mCardsArray) {
			if (!(c instanceof AppUpdateUICard)) {
				continue;
			}
			AppUpdateUICard uicard = (AppUpdateUICard) c;
			AppUpdateModel m = uicard.getAppUpdateModel();
			if (m == null) {
				continue;
			}

			String dlId = DownloadUtils.generateDownloadId(m.getPackageName(), m.getVersionCode());
			if (dlId.equals(di.getId())) {
				uicard.onDownloadChanged(di);
				mSectionAdapter.notifyDataSetChanged();
				return;
			}
		}

	}

	@Override
	public void onDownloadRemoved(String id) {
		super.onDownloadRemoved(id);

		if (mCardsArray == null || mCardsArray.size() == 0) {
			return;
		}

		for (Card c : mCardsArray) {
			if (!(c instanceof AppUpdateUICard)) {
				continue;
			}
			AppUpdateUICard uicard = (AppUpdateUICard) c;
			AppUpdateModel m = uicard.getAppUpdateModel();
			if (m == null) {
				continue;
			}

			String dlId = DownloadUtils.generateDownloadId(m.getPackageName(), m.getVersionCode());
			if (dlId.equals(id)) {
				uicard.onDownloadRemoved(id);
				mSectionAdapter.notifyDataSetChanged();
				return;
			}
		}
	}

}
